<template>
    <div class="appointment-page">
        <div class="date-picker-container">
            <div class="date-picker-header">
                <div class="header-left">
                    <el-icon>
                        <Calendar />
                    </el-icon>
                    <span class="date-picker-title">预约管理</span>
                    <el-tooltip content="点击添加按钮可以新增预约" placement="top" effect="light">
                        <el-icon class="help-icon">
                            <QuestionFilled />
                        </el-icon>
                    </el-tooltip>
                </div>

                <div class="header-actions">
                    <el-button type="primary" @click="openBookingDialog(null, null, 'add')" class="add-appointment-btn">
                        <el-icon class="plus-icon">
                            <Plus />
                        </el-icon>
                        添加预约
                    </el-button>
                </div>
            </div>
            <div class="date-buttons-container">
                <div class="date-buttons">
                    <el-button v-for="date in dateButtons" :key="date.value"
                        :type="date.isSelected ? 'success' : 'default'" size="small" @click="selectDate(date.value)"
                        class="date-button" :class="{ 'selected-date': date.isSelected }">
                        {{ date.label }}
                        <el-badge v-if="(appointmentStats[date.value] ?? 0) > 0"
                            :value="appointmentStats[date.value] ?? 0" class="appointment-badge" type="success" />
                    </el-button>
                </div>
            </div>
        </div>

        <div class="appointment-main">
            <!-- 标签页切换 -->
            <el-tabs v-model="activeMainTab" @tab-change="handleMainTabChange" class="main-tabs">
                <!-- 快速预约标签页 -->
                <el-tab-pane label="快速预约" name="quick">
                    <div class="dimensions-container">
                        <!-- 房间维度 -->
                        <div class="dimension-container room-dimension">
                            <div class="dimension-header">
                                <el-icon>
                                    <House />
                                </el-icon>
                                <span class="dimension-title">房间</span>
                                <el-tooltip content="点击房间卡片可以快速预约该房间,点击X可以取消预约,点击展开未来日期可以查看未来日期预约,边框为黄色的表示当前正在治疗"
                                    placement="top" effect="light">
                                    <el-icon class="help-icon">
                                        <QuestionFilled />
                                    </el-icon>
                                </el-tooltip>
                            </div>
                            <div class="room-cards">
                                <div v-for="(room, index) in rooms" :key="index" class="card room-card"
                                    :class="{ 'current-appointment': room.is_current }"
                                    @click="openBookingDialog(room, null, 'room')">
                                    <div class="card-title">{{ room.room_name }}</div>
                                    <div class="card-content">
                                        <div class="today-title">
                                            {{ dayjs().format('YYYY-MM-DD') === selectedDate ? '今日' :
                                                dayjs(selectedDate).format('MM-DD') }}
                                        </div>
                                        <div v-for="item in getTodayAppointments(room.childrens)" :key="item.id">
                                            <span class="today-appointment">
                                                <span class="appointment-info"
                                                    @click.stop="openEditDialog(item, 'room')" style="cursor: pointer;">
                                                    {{ formatAppointmentTime(item.start_time, item.end_time) }}
                                                    {{ item.medical_staff_name || '' }}:
                                                    {{ item.patient_name || '' }}
                                                </span>
                                                <el-button class="cancel-btn" type="danger" size="small"
                                                    @click.stop="openCancelDialog(item)">X</el-button>
                                            </span>
                                            <div v-if="item.symptoms" class="symptoms-line">
                                                <el-tooltip placement="top" effect="light">
                                                    <template #content>
                                                        <div style="
                                                    max-width: 400px;
                                                    word-wrap: break-word;
                                                    white-space: normal;
                                                    line-height: 1.5;
                                                    font-size: 14px;
                                                    padding: 8px;
                                                ">
                                                            {{ item.symptoms }}
                                                        </div>
                                                    </template>
                                                    <span class="symptoms-text">{{ item.symptoms }}</span>
                                                </el-tooltip>
                                            </div>
                                        </div>
                                        <template v-if="roomFutureCounts[room.room_id]">
                                            <el-button link type="primary" class="more-btn future-title"
                                                @click.stop="toggleFutureAppointments(room.room_id)">
                                                展开未来日期({{ roomFutureCounts[room.room_id] }}条)
                                                <el-icon class="arrow-icon"
                                                    :class="{ 'is-expanded': futureAppointmentsExpandedMap[room.room_id] }">
                                                    <ArrowDown />
                                                </el-icon>
                                            </el-button>
                                            <div v-if="futureAppointmentsExpandedMap[room.room_id]"
                                                v-for="item in getFutureAppointments(room.childrens)" :key="item.id">
                                                <span class="not-today-appointment">
                                                    <span class="appointment-info"
                                                        @click.stop="openEditDialog(item, 'room')"
                                                        style="cursor: pointer;">
                                                        {{ formatAppointmentTime(item.start_time, item.end_time) }}
                                                        {{ item.medical_staff_name || '' }}:
                                                        {{ item.patient_name || '' }}
                                                    </span>
                                                    <el-button class="cancel-btn" type="info" size="small"
                                                        @click.stop="openCancelDialog(item)">X</el-button>
                                                </span>
                                                <div v-if="item.symptoms" class="symptoms-line">
                                                    <el-tooltip placement="top" effect="light">
                                                        <template #content>
                                                            <div style="
                                                        max-width: 400px;
                                                        word-wrap: break-word;
                                                        white-space: normal;
                                                        line-height: 1.5;
                                                        font-size: 14px;
                                                        padding: 8px;
                                                    ">
                                                                {{ item.symptoms }}
                                                            </div>
                                                        </template>
                                                        <span class="symptoms-text">{{ item.symptoms }}</span>
                                                    </el-tooltip>
                                                </div>
                                            </div>
                                        </template>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 治疗师维度 -->
                        <div class="dimension-container medical-dimension">
                            <div class="dimension-header">
                                <el-icon>
                                    <User />
                                </el-icon>
                                <span class="dimension-title">治疗师</span>
                                <el-tooltip content="点击治疗师卡片可以快速预约该治疗师,点击X可以取消预约,点击展开未来日期可以查看未来日期预约,边框为红色的当前正在治疗"
                                    placement="top" effect="light">
                                    <el-icon class="help-icon">
                                        <QuestionFilled />
                                    </el-icon>
                                </el-tooltip>
                            </div>
                            <div class="medical-cards">
                                <div v-for="(med, index) in medicals" :key="index" class="card medical-card"
                                    :class="{ 'current-appointment': med.is_current }"
                                    @click="openBookingDialog(null, med, 'medical')">
                                    <div class="card-title">{{ med.medical_staff_name }}</div>
                                    <div class="card-content">
                                        <div class="today-title">
                                            {{ dayjs().format('YYYY-MM-DD') === selectedDate ? '今日' :
                                                dayjs(selectedDate).format('MM-DD') }}
                                        </div>
                                        <div v-for="item in getTodayAppointments(med.childrens)" :key="item.id">
                                            <span class="today-appointment">
                                                <span class="appointment-info"
                                                    @click.stop="openEditDialog(item, 'medical')"
                                                    style="cursor: pointer;">
                                                    {{ formatAppointmentTime(item.start_time, item.end_time) }}
                                                    {{ item.room_name || '' }}:
                                                    {{ item.patient_name || '' }}
                                                </span>
                                                <el-button class="cancel-btn" type="danger" size="small"
                                                    @click.stop="openCancelDialog(item)">X</el-button>
                                            </span>
                                            <div v-if="item.symptoms" class="symptoms-line">
                                                <el-tooltip placement="top" effect="light">
                                                    <template #content>
                                                        <div style="
                                                    max-width: 400px;
                                                    word-wrap: break-word;
                                                    white-space: normal;
                                                    line-height: 1.5;
                                                    font-size: 14px;
                                                    padding: 8px;
                                                ">
                                                            {{ item.symptoms }}
                                                        </div>
                                                    </template>
                                                    <span class="symptoms-text">{{ item.symptoms }}</span>
                                                </el-tooltip>
                                            </div>
                                        </div>
                                        <template v-if="medicalFutureCounts[med.medical_staff_id]">
                                            <el-button link type="primary" class="more-btn future-title"
                                                @click.stop="toggleFutureMedicalAppointments(med.medical_staff_id)">
                                                展开未来日期({{ medicalFutureCounts[med.medical_staff_id] }}条)
                                                <el-icon class="arrow-icon"
                                                    :class="{ 'is-expanded': futureMedicalAppointmentsExpandedMap[med.medical_staff_id] }">
                                                    <ArrowDown />
                                                </el-icon>
                                            </el-button>
                                            <div v-if="futureMedicalAppointmentsExpandedMap[med.medical_staff_id]"
                                                v-for="item in getFutureAppointments(med.childrens)" :key="item.id">
                                                <span class="not-today-appointment">
                                                    <span class="appointment-info"
                                                        @click.stop="openEditDialog(item, 'medical')"
                                                        style="cursor: pointer;">
                                                        {{ formatAppointmentTime(item.start_time, item.end_time) }}
                                                        {{ item.room_name || '' }}:
                                                        {{ item.patient_name || '' }}
                                                    </span>
                                                    <el-button class="cancel-btn" size="small"
                                                        @click.stop="openCancelDialog(item)">X</el-button>
                                                </span>
                                                <div v-if="item.symptoms" class="symptoms-line">
                                                    <el-tooltip placement="top" effect="light">
                                                        <template #content>
                                                            <div style="
                                                        max-width: 400px;
                                                        word-wrap: break-word;
                                                        white-space: normal;
                                                        line-height: 1.5;
                                                        font-size: 14px;
                                                        padding: 8px;
                                                    ">
                                                                {{ item.symptoms }}
                                                            </div>
                                                        </template>
                                                        <span class="symptoms-text">{{ item.symptoms }}</span>
                                                    </el-tooltip>
                                                </div>
                                            </div>
                                        </template>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-tab-pane>

                <!-- 预约记录标签页 -->
                <el-tab-pane label="预约记录" name="records">
                    <AppointmentTable :selected-date="selectedDate" ref="appointmentTableRef"
                        @edit-appointment="handleEditAppointment" @refresh-appointments="handleRefreshAppointments" />
                </el-tab-pane>
            </el-tabs>
        </div>

        <!-- 预约弹窗 -->
        <el-dialog v-model="showBookingDialog" width="600px" :title="`预约 - ${adminInfo.currentStore.name}`"
            :close-on-click-modal="false" :close-on-press-escape="false" :show-close="true" draggable>
            <el-tabs v-model="activeTab" class="dialog-tabs">
                <!-- 新增预约表单 -->
                <el-tab-pane label="新增预约" name="add">
                    <el-form :model="bookingForm" label-width="80px">
                        <el-form-item label="房间" :required="!isAddMode">
                            <el-select v-model="bookingForm.room_id" :disabled="bookingForm.room_locked" filterable
                                remote reserve-keyword :remote-method="fetchRooms" :loading="roomPagination.loading"
                                placeholder="请选择房间" @change="onRoomChange">
                                <el-option v-for="room in 表单房间数据" :key="room.id" :label="room.name" :value="room.id" />
                                <template #footer>
                                    <el-pagination v-if="roomPagination.total > roomPagination.pageSize" size="small"
                                        layout="prev, pager, next" :total="roomPagination.total"
                                        :page-size="roomPagination.pageSize" :current-page="roomPagination.page"
                                        @current-change="handleRoomPageChange" />
                                </template>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="治疗师" :required="!isAddMode">
                            <el-select v-model="bookingForm.medical_staff_id" :disabled="bookingForm.medical_locked"
                                filterable remote reserve-keyword :remote-method="fetchMedicals"
                                :loading="medicalPagination.loading" placeholder="请选择治疗师">
                                <el-option v-for="med in 表单治疗师数据" :key="med.id" :label="med.name" :value="med.id" />
                                <template #footer>
                                    <el-pagination v-if="medicalPagination.total > medicalPagination.pageSize"
                                        size="small" layout="prev, pager, next" :total="medicalPagination.total"
                                        :page-size="medicalPagination.pageSize" :current-page="medicalPagination.page"
                                        @current-change="handleMedicalPageChange" />
                                </template>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="养生项目">
                            <div style="margin-bottom: 5px;">
                                <el-button type="primary" :icon="Plus" @click="addHealthItemSelection" size="small">
                                    添加项目
                                </el-button>
                            </div>
                            <div v-for="(selection, index) in bookingForm.healthItemSelections" :key="index"
                                style="margin-bottom: 5px; width: 100%;">
                                <div style="display: flex; align-items: center; width: 100%; gap: 10px;">
                                    <el-select v-model="selection.health_item_id" filterable remote reserve-keyword
                                        :remote-method="fetchFormHealthItems" :loading="healthItemPagination.loading"
                                        placeholder="请选择养生项目" style="flex: 1" @change="onHealthItemChange(index)">
                                        <el-option v-for="(item, index) in healthItemOptions" :key="index"
                                            :label="item?.name || '未知项目'" :value="item?.id">
                                            <span>{{ item?.name || '未知项目' }}</span>
                                            <span style="float: right; color: #8492a6; font-size: 13px;">{{
                                                item?.duration || 0
                                                }}分钟</span>
                                        </el-option>
                                        <template #footer>
                                            <el-pagination
                                                v-if="healthItemPagination.total > healthItemPagination.pageSize"
                                                size="small" layout="prev, pager, next"
                                                :total="healthItemPagination.total"
                                                :page-size="healthItemPagination.pageSize"
                                                :current-page="healthItemPagination.page"
                                                @current-change="handleHealthItemPageChange" />
                                        </template>
                                    </el-select>
                                    <el-button type="danger" :icon="Minus" @click="removeHealthItemSelection(index)"
                                        size="small" style="flex-shrink: 0;">
                                        删除
                                    </el-button>
                                </div>
                            </div> 
                            <div v-if="totalHealthItemDuration > 0" class="total-duration"
                                style="margin-top: 5px; color: #409EFF; font-weight: bold;font-size:12px;">
                                总时长(分钟): {{ totalHealthItemDurationDetail || totalHealthItemDuration }}
                            </div>
                        </el-form-item>

                        <el-form-item label="选择时间" required>
                            <el-date-picker v-model="bookingForm.appointment_date" type="date" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD" :clearable="false" placeholder="选择日期" style="width: 120px"
                                :disabled-date="(time: Date) => time.getTime() < Date.now() - 8.64e7" />
                            <el-time-picker v-model="bookingForm.start_time" 
                                style="width: 120px; margin-left: 5px;" 
                                placeholder="开始时间" 
                                format="HH:mm" 
                                value-format="HH:mm"
                                :picker-options="{
                                    start: '08:00',
                                    end: '22:00'
                                }"
                                @change="updateBookingFormEndTime"
                                @input="formatTimeInput"/>
                            <span style="margin: 0 5px;">结束时间: {{ bookingForm.end_time || '自动计算' }}</span>
                        </el-form-item>
                        <el-form-item label="患者姓名">
                            <el-input v-model="bookingForm.patient_name" />
                        </el-form-item>
                        <el-form-item label="患者性别">
                            <el-radio-group v-model="bookingForm.patient_gender">
                                <el-radio :value="1">男</el-radio>
                                <el-radio :value="2">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="手机号">
                            <el-input v-model="bookingForm.patient_phone" maxlength="11"
                                oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入手机号" />
                        </el-form-item>
                        <el-form-item label="备注">
                            <el-input v-model="bookingForm.symptoms" type="textarea" />
                        </el-form-item>
                    </el-form>
                </el-tab-pane>

                <!-- 编辑预约表单 -->
                <el-tab-pane label="编辑预约" name="edit">
                    <el-form :model="editForm" label-width="80px">
                        <!-- <el-form-item label="预约ID" required>
                            <el-input v-model="editForm.appointment_id" disabled />
                        </el-form-item> -->
                        <el-form-item label="房间" required>
                            <el-select v-model="editForm.room_id" :disabled="editForm.room_locked" filterable
                                remote reserve-keyword :remote-method="fetchRooms" :loading="roomPagination.loading"
                                placeholder="请选择房间" @change="onEditRoomChange">
                                <el-option v-for="room in 表单房间数据" :key="room.id" :label="room.name" :value="room.id" />
                                <template #footer>
                                    <el-pagination v-if="roomPagination.total > roomPagination.pageSize" size="small"
                                        layout="prev, pager, next" :total="roomPagination.total"
                                        :page-size="roomPagination.pageSize" :current-page="roomPagination.page"
                                        @current-change="handleRoomPageChange" />
                                </template>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="治疗师" required>
                            <el-select v-model="editForm.medical_staff_id" :disabled="editForm.medical_locked"
                                filterable remote reserve-keyword :remote-method="fetchMedicals"
                                :loading="medicalPagination.loading" placeholder="请选择治疗师">
                                <el-option v-for="med in 表单治疗师数据" :key="med.id" :label="med.name" :value="med.id" />
                                <template #footer>
                                    <el-pagination v-if="medicalPagination.total > medicalPagination.pageSize"
                                        size="small" layout="prev, pager, next" :total="medicalPagination.total"
                                        :page-size="medicalPagination.pageSize" :current-page="medicalPagination.page"
                                        @current-change="handleMedicalPageChange" />
                                </template>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="养生项目">
                            <div style="margin-bottom: 5px;">
                                <el-button type="primary" :icon="Plus" @click="addEditHealthItemSelection" size="small">
                                    添加项目
                                </el-button>
                            </div>
                            <div v-for="(selection, index) in editForm.healthItemSelections" :key="index"
                                style="margin-bottom: 5px; width: 100%;">
                                <div style="display: flex; align-items: center; width: 100%; gap: 10px;">
                                    <el-select v-model="selection.health_item_id" filterable remote reserve-keyword
                                        :remote-method="fetchFormHealthItems" :loading="healthItemPagination.loading"
                                        placeholder="请选择养生项目" style="flex: 1;" @change="onEditHealthItemChange(index)">
                                        <el-option v-for="(item, index) in healthItemOptions"
                                            :key="item?.id || Math.random()" :label="item?.name || '未知项目'"
                                            :value="item?.id">
                                            <span>{{ item?.name || '未知项目' }}</span>
                                            <span style="float: right; color: #8492a6; font-size: 13px;">{{
                                                item?.duration || 0
                                                }}分钟</span>
                                        </el-option>
                                        <template #footer>
                                            <el-pagination
                                                v-if="healthItemPagination.total > healthItemPagination.pageSize"
                                                size="small" layout="prev, pager, next"
                                                :total="healthItemPagination.total"
                                                :page-size="healthItemPagination.pageSize"
                                                :current-page="healthItemPagination.page"
                                                @current-change="handleHealthItemPageChange" />
                                        </template>
                                    </el-select>
                                    <el-button type="danger" :icon="Minus" @click="removeEditHealthItemSelection(index)"
                                        size="small" style="flex-shrink: 0;">
                                        删除
                                    </el-button>
                                </div>
                            </div>
                            <div v-if="totalEditHealthItemDuration > 0" class="total-duration"
                                style="color: #409EFF; font-weight: bold; font-size: 10px;;font-size:12px;">
                                总时长(分钟): {{ totalEditHealthItemDurationDetail || totalEditHealthItemDuration  }}
                            </div>
                        </el-form-item>
                        <el-form-item label="选择时间" required>
                            <el-date-picker v-model="editForm.appointment_date" type="date" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD" :clearable="false" placeholder="选择日期" style="width: 120px"
                                :disabled-date="(time: Date) => time.getTime() < Date.now() - 8.64e7" />
                            <el-time-picker v-model="editForm.start_time" 
                                style="width: 120px; margin-left: 5px;" 
                                placeholder="开始时间" 
                                format="HH:mm" 
                                value-format="HH:mm"
                                :picker-options="{
                                    start: '08:00',
                                    step: '00:05',
                                    end: '22:00'
                                }"
                                @change="updateEditFormEndTime" 
                                @input="formatEditTimeInput" />
                            <span style="margin: 0 5px;">结束时间: {{ editForm.end_time || '自动计算' }}</span>
                        </el-form-item>
                        <el-form-item label="患者姓名">
                            <el-input v-model="editForm.patient_name" />
                        </el-form-item>
                        <el-form-item label="患者性别">
                            <el-radio-group v-model="editForm.patient_gender">
                                <el-radio :value="1">男</el-radio>
                                <el-radio :value="2">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="手机号">
                            <el-input v-model="editForm.patient_phone" maxlength="11"
                                oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入手机号" />
                        </el-form-item>
                        <el-form-item label="备注">
                            <el-input v-model="editForm.symptoms" type="textarea" />
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
            <template #footer>
                <el-button @click="showBookingDialog = false">取消</el-button>
                <el-button type="primary" @click="submitBooking">{{ activeTab === 'edit' ? '更新' : '添加' }}</el-button>
            </template>
        </el-dialog>


    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAdminInfo } from '/@/stores/adminInfo'
import { House, User, QuestionFilled, Calendar, ArrowDown, Plus, Minus } from '@element-plus/icons-vue'
import createAxios from '/@/utils/axios'
import dayjs from 'dayjs'
import AppointmentTable from './AppointmentTable.vue'

const adminInfo = useAdminInfo()
interface RoomData {
    room_id: string
    room_name: string
    is_current?: number
    childrens: AppointmentData[]
}

interface MedicalData {
    medical_staff_id: string
    medical_staff_name: string
    is_current?: number
    childrens: AppointmentData[]
}

interface AppointmentData {
    id: number
    appointment_id: number
    room_id: string
    room_name: string
    medical_staff_id: string
    medical_staff_name: string
    start_time: string
    end_time: string
    patient_name: string
    patient_phone: string
    is_current?: number
    symptoms: string
}

const rooms = ref<RoomData[]>([]) //后台返回的房间数据
const medicals = ref<MedicalData[]>([]) //后台返回的治疗师数据
const 表单房间数据 = ref<any[]>([])
const 表单治疗师数据 = ref<any[]>([])
const showBookingDialog = ref(false)
const activeTab = ref('add') // 当前激活的tab
const activeMainTab = ref('quick') // 主标签页，默认显示快速预约
const appointmentTableRef = ref() // 预约记录表格组件引用
const currentEditingAppointment = ref<any>(null) // 当前编辑的预约记录
let timer: number | null = null
const selectedDate = ref(dayjs().format('YYYY-MM-DD')) // 用户在快速日期行选中的日期
// 日期选择按钮数据
const dateButtons = ref<Array<{ value: string; label: string; isSelected: boolean }>>([])
// 预约统计数据
const appointmentStats = ref<{ [date: string]: number }>({})

// 生成两周的日期按钮
function generateDateButtons() {
    const buttons = []
    const today = dayjs()

    for (let i = 0; i < 10; i++) {
        const date = today.add(i, 'day')
        const value = date.format('YYYY-MM-DD')
        const label = i === 0 ? '今天' : date.format('YYYY-MM-DD')
        const isSelected = value === selectedDate.value

        buttons.push({
            value,
            label,
            isSelected,
        })
    }

    dateButtons.value = buttons
}

// 选择日期
function selectDate(date: string) {
    selectedDate.value = date
    bookingForm.value.appointment_date = date
    // 更新按钮的选中状态
    dateButtons.value.forEach((button) => {
        button.isSelected = button.value === date
    })
    // 移除手动刷新调用，让 AppointmentTable 的 watch 监听器自动处理
}

// 处理主标签页切换
function handleMainTabChange(tabName: string | number) {
    if (tabName === 'records' && appointmentTableRef.value) {
        // 切换到预约记录标签页时，刷新表格数据
        appointmentTableRef.value.refresh()
    }
}

// 添加分页相关数据
const roomPagination = ref({
    page: 1,
    pageSize: 10,
    total: 0,
    loading: false,
})

const medicalPagination = ref({
    page: 1,
    pageSize: 10,
    total: 0,
    loading: false,
})

const bookingForm = ref({
    room_id: undefined,
    room_locked: false,
    medical_staff_id: undefined,
    medical_locked: false,
    appointment_date: dayjs().format('YYYY-MM-DD'),
    start_time: '',
    end_time: '',
    patient_name: '',
    patient_gender: 1,
    patient_phone: '',
    symptoms: '',
    healthItemSelections: [{ health_item_id: undefined, duration: 0, name: '' }],
})

// 编辑表单数据
const editForm = ref({
    appointment_id: '',
    room_id: undefined,
    room_locked: false,
    medical_staff_id: undefined,
    medical_locked: false,
    appointment_date: dayjs().format('YYYY-MM-DD'),
    start_time: '',
    end_time: '',
    patient_name: '',
    patient_gender: 1,
    patient_phone: '',
    symptoms: '',
    healthItemSelections: [{ health_item_id: undefined, duration: 0, name: '' }],
})

// 养生项目选项数据 - 统一使用healthItemOptions 
const healthItemOptions = ref<any[]>([])

// 养生项目分页数据
const healthItemPagination = ref({
    page: 1,
    pageSize: 20,
    total: 0,
    loading: false,
})

// 计算总时长 - 包含房间时长和养生项目时长
const totalHealthItemDuration = computed(() => {
    const healthItemDuration = bookingForm.value.healthItemSelections.reduce((total, selection) => {
        return total + (selection.duration || 0)
    }, 0)
    
    // 选择了房间则增加15分钟
    const roomDuration = bookingForm.value.room_id ? 15 : 0
    
    return healthItemDuration + roomDuration
})

// 计算总时长详细分解显示
const totalHealthItemDurationDetail = computed(() => {
    const healthItemDurations = bookingForm.value.healthItemSelections
        .filter(selection => selection.duration && selection.duration > 0)
        .map(selection => selection.duration)
    
    const roomDuration = bookingForm.value.room_id ? 15 : 0
    
    if (healthItemDurations.length === 0 && roomDuration === 0) {
        return ''
    }
    
    const allDurations = [...healthItemDurations]
    if (roomDuration > 0) {
        allDurations.push(roomDuration)
    }
    
    const total = allDurations.reduce((sum, duration) => sum + duration, 0)
    const detail = allDurations.join('+')
    
    return `${total} (${detail})`
})

// 计算编辑表单总时长 - 包含房间时长和养生项目时长
const totalEditHealthItemDuration = computed(() => {
    const healthItemDuration = editForm.value.healthItemSelections.reduce((total, selection) => {
        return total + (selection.duration || 0)
    }, 0)
    
    // 选择了房间则增加15分钟
    const roomDuration = editForm.value.room_id ? 15 : 0
    
    return healthItemDuration + roomDuration
})

// 计算编辑表单总时长详细分解显示
const totalEditHealthItemDurationDetail = computed(() => {
    const healthItemDurations = editForm.value.healthItemSelections
        .filter(selection => selection.duration && selection.duration > 0)
        .map(selection => selection.duration)
    
    const roomDuration = editForm.value.room_id ? 15 : 0
    
    if (healthItemDurations.length === 0 && roomDuration === 0) {
        return ''
    }
    
    const allDurations = [...healthItemDurations]
    if (roomDuration > 0) {
        allDurations.push(roomDuration)
    }
    
    const total = allDurations.reduce((sum, duration) => sum + duration, 0)
    const detail = allDurations.join('+')
    
    return `${total} (${detail})`
})

// 判断是否为添加预约模式
const isAddMode = computed(() => {
    return activeTab.value === 'add' && !currentEditingAppointment.value
})

// 养生项目相关方法
function onHealthItemChange(index: number) {
    // 项目选择变化时，将选中项目的duration存储到selection中
    const selection = bookingForm.value.healthItemSelections[index]
    if (selection && selection.health_item_id) {
        const selectedItem = healthItemOptions.value.find(item => item.id === selection.health_item_id)
        if (selectedItem) {
            selection.duration = selectedItem.duration || 0
            selection.name = selectedItem.name
        }
    }
    updateBookingFormEndTime()

    // 预加载所有已选择的养生项目，确保跨页显示正确
    preloadSelectedHealthItems()
}

// 预加载已选择的养生项目到选项中，确保能正确显示名称
function preloadSelectedHealthItems() {
    bookingForm.value.healthItemSelections.forEach((selection: any) => {
        if (selection.health_item_id) {
            const existingItem = healthItemOptions.value.find(option => option.id === selection.health_item_id)
            if (!existingItem && selection.name) {
                // 如果选项中没有这个项目，但selection中有名称，添加到列表开头
                healthItemOptions.value.unshift({
                    id: selection.health_item_id,
                    name: selection.name,
                    duration: selection.duration || 0,
                })
            }
        }
    })
}

// 编辑表单养生项目选择变化处理
function onEditHealthItemChange(index: number) {
    // 项目选择变化时，将选中项目的duration存储到selection中
    const selection = editForm.value.healthItemSelections[index]
    if (selection && selection.health_item_id) {
        const selectedItem = healthItemOptions.value.find(item => item.id === selection.health_item_id)
        if (selectedItem) {
            selection.duration = selectedItem.duration || 0
            selection.name = selectedItem.name
        }
    }
    updateEditFormEndTime()

    // 预加载所有已选择的养生项目，确保跨页显示正确
    preloadEditSelectedHealthItems()
}

// 预加载编辑表单已选择的养生项目到选项中，确保能正确显示名称
function preloadEditSelectedHealthItems() {
    editForm.value.healthItemSelections.forEach((selection: any) => {
        if (selection.health_item_id) {
            const existingItem = healthItemOptions.value.find(option => option.id === selection.health_item_id)
            if (!existingItem && selection.name) {
                // 如果选项中没有这个项目，但selection中有名称，添加到列表开头
                healthItemOptions.value.unshift({
                    id: selection.health_item_id,
                    name: selection.name,
                    duration: selection.duration || 0,
                })
            }
        }
    })
}

function updateBookingFormEndTime() {
    if (bookingForm.value.start_time && totalHealthItemDuration.value > 0) {
        const startTime = dayjs(`2000-01-01 ${bookingForm.value.start_time}`)
        const endTime = startTime.add(totalHealthItemDuration.value, 'minute')
        bookingForm.value.end_time = endTime.format('HH:mm')
    }
}

function updateEditFormEndTime() {
    if (editForm.value.start_time && totalEditHealthItemDuration.value > 0) {
        const startTime = dayjs(`2000-01-01 ${editForm.value.start_time}`)
        const endTime = startTime.add(totalEditHealthItemDuration.value, 'minute')
        editForm.value.end_time = endTime.format('HH:mm')
    }
}

function isHealthItemSelected(itemId: any) {
    return bookingForm.value.healthItemSelections.some(selection => selection.health_item_id === itemId)
}

function addHealthItemSelection() {
    bookingForm.value.healthItemSelections.push({ health_item_id: undefined, duration: 0, name: '' })
}

function removeHealthItemSelection(index: number) {
    if (bookingForm.value.healthItemSelections.length > 0) {
        bookingForm.value.healthItemSelections.splice(index, 1)
        updateBookingFormEndTime()
    }
}

// 编辑表单养生项目相关方法
function addEditHealthItemSelection() {
    editForm.value.healthItemSelections.push({ health_item_id: undefined, duration: 0, name: '' })
}

function removeEditHealthItemSelection(index: number) {
    if (editForm.value.healthItemSelections.length > 0) {
        editForm.value.healthItemSelections.splice(index, 1)
        updateEditFormEndTime()
    }
}

// 统一的时间输入格式化函数
function formatTimeValue(value: string): string {
    if (!value) {
        return ''
    }

    // 移除所有非数字字符
    let cleanValue = value.replace(/\D/g, '')

    // 限制最大长度为4位数字
    if (cleanValue.length > 4) {
        cleanValue = cleanValue.slice(0, 4)
    }

    // 只有在输入长度为2位或4位时才进行格式化
    if (cleanValue.length === 2) {
        // 验证小时数（00-23）
        let validHours = parseInt(cleanValue) || 0
        if (validHours > 23) {
            validHours = 23
        }
        return String(validHours).padStart(2, '0')
    } else if (cleanValue.length === 4) {
        const hours = cleanValue.slice(0, 2)
        const minutes = cleanValue.slice(2, 4)

        // 验证小时数（00-23）
        let validHours = parseInt(hours) || 0
        if (validHours > 23) {
            validHours = 23
        }

        // 验证分钟数（00-59）
        let validMinutes = parseInt(minutes) || 0
        if (validMinutes > 59) {
            validMinutes = 59
        }

        return `${String(validHours).padStart(2, '0')}:${String(validMinutes).padStart(2, '0')}`
    }

    // 其他情况直接返回原值（1位或3位数字）
    return cleanValue
}

// 新增预约时间输入格式化
function formatTimeInput(value: string) {
    const formattedValue = formatTimeValue(value)
    bookingForm.value.start_time = formattedValue
    updateBookingFormEndTime()
}

// 编辑预约时间输入格式化
function formatEditTimeInput(value: string) {
    const formattedValue = formatTimeValue(value)
    editForm.value.start_time = formattedValue
    updateEditFormEndTime()
}

// 远程搜索养生项目
function fetchFormHealthItems(query: string) {
    healthItemPagination.value.loading = true
    createAxios({
        url: '/admin/HealthItems',
        method: 'get',
        params: {
            quickSearch: query,
            page: healthItemPagination.value.page,
            limit: healthItemPagination.value.pageSize,
        },
    }).then((res) => {
        healthItemOptions.value = res.data.list || res.data || []
        healthItemPagination.value.total = res.data.total || healthItemOptions.value.length
        healthItemPagination.value.loading = false

        // 获取数据后立即预加载已选择的项目
        preloadSelectedHealthItems()
        preloadEditSelectedHealthItems()
    }).catch(() => {
        healthItemOptions.value = []
        healthItemPagination.value.loading = false
    })
}

// 房间选择变化处理
function onRoomChange() {
    updateBookingFormEndTime()
}

// 编辑表单房间选择变化处理
function onEditRoomChange() {
    updateEditFormEndTime()
}

// 养生项目分页变化
function handleHealthItemPageChange(page: number) {
    healthItemPagination.value.page = page
    fetchFormHealthItems('')

    // 翻页后立即预加载已选择的项目，确保显示正确
    // preloadSelectedHealthItems()
    // preloadEditSelectedHealthItems()
}

// 获取开始时间
const getStartTime = computed(() => {
    if (bookingForm.value.appointment_date) {
        const isToday = dayjs(bookingForm.value.appointment_date).format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD')
        if (isToday) {
            const currentTime = dayjs().subtract(1, 'hour')
            const roundedTime = currentTime.minute(Math.floor(currentTime.minute() / 5) * 5)
            return roundedTime.format('HH:mm')
        }
    }
    return '08:00'
})

// 控制每个房间的未来预约展开状态
const futureAppointmentsExpandedMap = ref<{ [roomId: string]: boolean }>({})

// 控制每个治疗师的未来预约展开状态
const futureMedicalAppointmentsExpandedMap = ref<{ [medicalId: string]: boolean }>({})

// 计算每个房间的未来预约数量
const roomFutureCounts = computed(() => {
    const counts: { [key: string]: number } = {}
    rooms.value.forEach((room) => {
        counts[room.room_id] = getFutureAppointmentCount(room.childrens)
    })
    return counts
})

// 计算每个治疗师的未来预约数量
const medicalFutureCounts = computed(() => {
    const counts: { [key: string]: number } = {}
    medicals.value.forEach((med) => {
        counts[med.medical_staff_id] = getFutureMedicalAppointmentCount(med.childrens)
    })
    return counts
})

// 远程搜索房间
function fetchRooms(query: string) {
    roomPagination.value.loading = true
    createAxios({
        url: '/admin/room/index',
        method: 'get',
        params: {
            quickSearch: query,
            page: roomPagination.value.page,
            limit: roomPagination.value.pageSize,
        },
    }).then((res) => {
        表单房间数据.value = res.data.list
        roomPagination.value.total = res.data.total
        roomPagination.value.loading = false
    })
}

// 远程搜索治疗师
function fetchMedicals(query: string) {
    medicalPagination.value.loading = true
    createAxios({
        url: '/admin/MedicalStaff/index',
        method: 'get',
        params: {
            quickSearch: query,
            page: medicalPagination.value.page,
            limit: medicalPagination.value.pageSize,
            select:true,
        },
    }).then((res) => {
        表单治疗师数据.value = res.data.list
        medicalPagination.value.total = res.data.total
        medicalPagination.value.loading = false
    })
}

// 房间分页变化
function handleRoomPageChange(page: number) {
    roomPagination.value.page = page
    fetchRooms('')
}

// 治疗师分页变化
function handleMedicalPageChange(page: number) {
    medicalPagination.value.page = page
    fetchMedicals('')
}

// 打开预约弹窗
function openBookingDialog(room: any, med: any, type: 'room' | 'medical' | 'add') {
    showBookingDialog.value = true
    // 重置表单
    bookingForm.value = {
        ...bookingForm.value,
        room_id: undefined,
        room_locked: false,
        medical_staff_id: undefined,
        medical_locked: false,
        start_time: '',
        end_time: '',
        patient_name: '',
        patient_gender: 1,
        patient_phone: '',
        symptoms: '',
        healthItemSelections: [],
    }

    if (type === 'room') {
        bookingForm.value.room_id = room.room_id
        bookingForm.value.room_locked = true
        // 预加载房间数据
        表单房间数据.value = [
            {
                id: room.room_id,
                name: room.room_name,
            },
        ]
    } else if (type === 'medical') {
        bookingForm.value.medical_staff_id = med.medical_staff_id
        bookingForm.value.medical_locked = true
        // 预加载治疗师数据
        表单治疗师数据.value = [
            {
                id: med.medical_staff_id,
                name: med.medical_staff_name,
            },
        ]
    }
    // 如果是直接添加，则预加载所有房间和治疗师数据
    if (type === 'add') {
        fetchRooms('')
        fetchMedicals('')
    }

    // 初始化养生项目数据
    fetchFormHealthItems('')

    // 设置为新增模式，切换到新增tab
    currentEditingAppointment.value = null
    activeTab.value = 'add'
    editForm.value = {
        ...editForm.value,
        appointment_id: '',
        room_id: undefined,
        room_locked: false,
        medical_staff_id: undefined,
        medical_locked: false,
        appointment_date: dayjs().format('YYYY-MM-DD'),
        start_time: '',
        end_time: '',
        patient_name: '',
        patient_gender: 1,
        patient_phone: '',
        symptoms: '',
        healthItemSelections: [],
    }

}

// 处理从表格点击编辑预约
function handleEditAppointment(appointment: any) {
    openEditDialog(appointment, 'table')
}

// 打开编辑预约弹窗
function openEditDialog(appointment: any, fromDimension: 'room' | 'medical' | 'table') {
    showBookingDialog.value = true
    currentEditingAppointment.value = appointment
    activeTab.value = 'edit' // 切换到编辑tab

    // 初始化编辑表单的养生项目数据
    fetchFormHealthItems('')

    // 预加载已选择的养生项目到选项中，确保能正确显示名称
    if (appointment.health_items && appointment.health_items.length > 0) {
        // 将已选择的养生项目添加到healthItemOptions中
        appointment.health_items.forEach((item: any) => {
            const existingItem = healthItemOptions.value.find(option => option.id === item.health_item_id)
            if (!existingItem) {
                healthItemOptions.value.push({
                    id: item.health_item_id,
                    name: item.name,
                    duration: item.duration || 0,
                    description: item.description || ''
                })
            }
        })
    }

    // 填充编辑表单数据
    editForm.value = {
        appointment_id: appointment.appointment_id || appointment.id || '',
        room_id: appointment.room_id,
        room_locked: fromDimension === 'room', // 只有从治疗师维度点击时才锁定房间选择
        medical_staff_id: appointment.medical_staff_id,
        medical_locked: fromDimension === 'medical', // 只有从房间维度点击时才锁定治疗师选择
        appointment_date: dayjs(appointment.start_time).format('YYYY-MM-DD'),
        start_time: dayjs(appointment.start_time).format('HH:mm'),
        end_time: dayjs(appointment.end_time).format('HH:mm'),
        patient_name: appointment.patient_name || '',
        patient_gender: appointment.patient_gender || 1,
        patient_phone: appointment.patient_phone || '',
        symptoms: appointment.symptoms || '',
        healthItemSelections: appointment.health_items && appointment.health_items.length > 0
            ? appointment.health_items.map((item: any) => ({
                health_item_id: item.health_item_id,
                name: item.name,
                duration: item.duration || 0
            }))
            : [{ health_item_id: undefined, duration: 0, name: '' }],
    }
    // 预加载对应的房间和治疗师数据，确保显示完整的名称信息
    if (fromDimension === 'room') {
        // 从房间维度点击，预加载房间数据，可以选择治疗师
        表单房间数据.value = [{
            id: appointment.room_id,
            name: appointment.room_name,
        }]
        // 预加载当前治疗师数据，确保显示名称
        if (appointment.medical_staff_id && appointment.medical_staff_name) {
            表单治疗师数据.value = [{
                id: appointment.medical_staff_id,
                name: appointment.medical_staff_name,
            }]
        }
        fetchMedicals('')
    } else if (fromDimension === 'medical') {
        // 从治疗师维度点击，预加载治疗师数据，可以选择房间
        表单治疗师数据.value = [{
            id: appointment.medical_staff_id,
            name: appointment.medical_staff_name,
        }]
        // 预加载当前房间数据，确保显示名称
        if (appointment.room_id && appointment.room_name) {
            表单房间数据.value = [{
                id: appointment.room_id,
                name: appointment.room_name,
            }]
        }
        fetchRooms('')
    } else {
        // 从表格点击，预加载房间和治疗师数据，都可以选择
        // 确保房间数据完整
        表单房间数据.value = [{
            id: appointment.room_id,
            name: appointment.room?.name || appointment.room_name,
        }]
        // 确保治疗师数据完整
        表单治疗师数据.value = [{
            id: appointment.medical_staff_id,
            name: appointment.medicalStaff?.name || appointment.medical_staff_name,
        }]
        fetchRooms('')
        fetchMedicals('')
    }
}

function beforeSubmitValidate(form: any, isAddMode: boolean = false): boolean {
    if (!form.value.start_time) {
        ElMessage.error('请输入开始时间')
        return false
    }

    const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/
    if (!timeRegex.test(form.value.start_time)) {
        ElMessage.error('请输入正确的时间格式（HH:mm），例如：09:30')
        return false
    }

    const digitsOnly = form.value.start_time.replace(':', '')
    if (digitsOnly.length < 4) {
        ElMessage.error('时间格式不完整，请输入完整的时间（HH:mm）')
        return false
    }

    // 在添加预约模式下，房间和医师不是必填项
    if (!isAddMode) {
        // 编辑模式下验证房间和医师
        if (!form.value.room_id) {
            ElMessage.error('请选择房间')
            return false
        }
        if (!form.value.medical_staff_id) {
            ElMessage.error('请选择医师')
            return false
        }
    }

    // 验证养生项目必填
    if (!form.value.healthItemSelections ||
        form.value.healthItemSelections.length === 0 ||
        !form.value.healthItemSelections.some((item: any) => item.health_item_id)) {
        ElMessage.error('请至少选择一个养生项目')
        return false
    }
    return true;
}
// 提交预约
function submitBooking() {
    let url, data
    // 新增模式验证

    if (activeTab.value === 'edit') {
        if (!beforeSubmitValidate(editForm)) {
            return
        }
        // 编辑模式验证
        if (!editForm.value.appointment_id) {
            ElMessage.error('预约ID不能为空')
            return
        }
        // 编辑时弹出确认对话框
        ElMessageBox.confirm(
            '确定要修改这个预约记录吗？',
            '确认修改',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            url = '/admin/appointment/edit'
            data = { ...editForm.value, id: editForm.value.appointment_id }

            createAxios({
                url,
                method: 'POST',
                data,
            }).then(() => {
                ElMessage.success('更新成功')
                showBookingDialog.value = false
                fetchData()
            })
        }).catch(() => {
            // 用户取消操作
        })

    } else {
        // 判断是否为添加预约模式（通过activeTab和currentEditingAppointment判断）
        const isAddMode = activeTab.value === 'add' && !currentEditingAppointment.value
        if (!beforeSubmitValidate(bookingForm, isAddMode)) {
            return
        }
        // 新增模式
        url = '/admin/appointment/add'
        data = { ...bookingForm.value }

        createAxios({
            url,
            method: 'POST',
            data,
        }).then(() => {
            ElMessage.success('预约成功')
            showBookingDialog.value = false
            fetchData()
        })
    }
}

// 判断是否为当天预约
function isTodayAppointment(startTime: string) {
    if (!startTime) return false
    return dayjs(startTime).format('YYYY-MM-DD') === bookingForm.value.appointment_date
}

// 格式化时间
function formatAppointmentTime(start: string, end: string) {
    if (!start || !end) return ''
    if (isTodayAppointment(start)) {
        return `${start.slice(11, 16)}-${end.slice(11, 16)}`
    }
    return `${dayjs(start).format('MM-DD')} ${start.slice(11, 16)}-${end.slice(11, 16)}`
}

// 获取今日预约
function getTodayAppointments(appointments: AppointmentData[]) {
    if (!appointments || !Array.isArray(appointments)) return []
    return getSortedAppointments(appointments.filter((i) => i.appointment_id && isTodayAppointment(i.start_time)))
}

// 获取未来预约
function getFutureAppointments(appointments: AppointmentData[]) {
    if (!appointments || !Array.isArray(appointments)) return []
    return getSortedAppointments(appointments.filter((i) => i.appointment_id && !isTodayAppointment(i.start_time)))
}

// 获取治疗师今日预约
// function getTodayMedicalAppointments(appointments: AppointmentData[]) {
//     if (!appointments || !Array.isArray(appointments)) return []
//     return getSortedAppointments(appointments.filter((i) => i.appointment_id && isTodayAppointment(i.start_time)))
// }

// // 获取治疗师未来预约
// function getFutureMedicalAppointments(appointments: AppointmentData[]) {
//     if (!appointments || !Array.isArray(appointments)) return []
//     return getSortedAppointments(appointments.filter((i) => i.appointment_id && !isTodayAppointment(i.start_time)))
// }

// 获取未来预约数量
function getFutureAppointmentCount(appointments: AppointmentData[]) {
    if (!appointments || !Array.isArray(appointments)) return 0
    return appointments.filter((i) => i.appointment_id && !isTodayAppointment(i.start_time)).length
}

// 获取治疗师未来预约数量
function getFutureMedicalAppointmentCount(appointments: AppointmentData[]) {
    if (!appointments || !Array.isArray(appointments)) return 0
    return appointments.filter((i) => i.appointment_id && !isTodayAppointment(i.start_time)).length
}

// 获取排序后的预约列表
function getSortedAppointments(appointments: any[]) {
    return [...appointments].sort((a, b) => {
        return new Date(a.start_time).getTime() - new Date(b.start_time).getTime()
    })
}

// 切换房间未来预约的展开状态
function toggleFutureAppointments(roomId: string) {
    futureAppointmentsExpandedMap.value[roomId] = !futureAppointmentsExpandedMap.value[roomId]
}

// 切换治疗师未来预约的展开状态
function toggleFutureMedicalAppointments(medicalId: string) {
    futureMedicalAppointmentsExpandedMap.value[medicalId] = !futureMedicalAppointmentsExpandedMap.value[medicalId]
}

// 取消预约
function openCancelDialog(appointment: any) {
    ElMessageBox.confirm('确定要取消该预约吗？', '取消预约', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            createAxios({
                url: '/admin/appointment/cancel',
                method: 'POST',
                data: {
                    id: appointment.appointment_id,
                    cancel_reason: '快速预约界面取消',
                },
            }).then(() => {
                ElMessage.success('取消预约成功')
                fetchData()
            })
        })
        .catch(() => {
            // 用户取消操作
        })
}
let 后台房间数据: any[] = []
let 后台治疗师数据: any[] = []

function fetchData() {
    createAxios({
        url: '/admin/appointment/quick',
        method: 'get',
        // params: {
        //     appointment_date: bookingForm.value.appointment_date,
        // },
    }).then((res) => {
        后台房间数据 = res.data.rooms
        后台治疗师数据 = res.data.medicals
        appointmentStats.value = res.data.appointment_stats
    })
}
// 检查并移除过期预约
function checkAndRemoveExpiredAppointments() {
    // 检查并移除过期预约
    const now = new Date()
    let 过滤后的房间数据: any[] = JSON.parse(JSON.stringify(后台房间数据)) //深拷贝
    let 过滤后的治疗师数据: any[] = JSON.parse(JSON.stringify(后台治疗师数据)) //深拷贝
    // 处理房间维度的预约
    过滤后的房间数据.forEach((room) => {
        room.is_current = 0
        //过滤数据
        if (room.childrens && Array.isArray(room.childrens)) {
            room.childrens = room.childrens.filter((appointment: any) => {
                if (appointment.appointment_id && appointment.end_time && appointment.start_time) {
                    const endTime = new Date(appointment.end_time)
                    // 使用JavaScript直接判断日期
                    const appointmentDate = appointment.start_time.split(' ')[0] // 获取日期部分 YYYY-MM-DD
                    if (appointmentDate === selectedDate.value) {
                        return endTime > now
                    }
                    return new Date(appointment.start_time) >= new Date(selectedDate.value)
                }
                return true // 保留没有预约的数据
            })

            // 数据过滤后，检查是否有当前预约
            if (room.childrens.length > 0) {
                const hasCurrentAppointment = room.childrens.some((appointment: any) => {
                    if (appointment.appointment_id && appointment.end_time && appointment.start_time) {
                        const endTime = new Date(appointment.end_time)
                        const startTime = new Date(appointment.start_time)
                        return startTime <= now && now <= endTime
                    }
                    return false
                })
                room.is_current = hasCurrentAppointment ? 1 : 0
            }
        }
    })

    // 处理治疗师维度的预约
    过滤后的治疗师数据.forEach((med) => {
        med.is_current = 0
        //过滤数据
        if (med.childrens && Array.isArray(med.childrens)) {
            med.childrens = med.childrens.filter((appointment: any) => {
                if (appointment.appointment_id && appointment.end_time && appointment.start_time) {
                    const endTime = new Date(appointment.end_time)
                    // 使用JavaScript直接判断日期
                    const appointmentDate = appointment.start_time.split(' ')[0] // 获取日期部分 YYYY-MM-DD
                    if (appointmentDate === selectedDate.value) {
                        return endTime > now
                    }
                    return new Date(appointment.start_time) >= new Date(selectedDate.value)
                }
                return true // 保留没有预约的数据
            })

            // 数据过滤后，检查是否有当前预约
            if (med.childrens.length > 0) {
                const hasCurrentAppointment = med.childrens.some((appointment: any) => {
                    if (appointment.appointment_id && appointment.end_time && appointment.start_time) {
                        const endTime = new Date(appointment.end_time)
                        const startTime = new Date(appointment.start_time)
                        return startTime <= now && now <= endTime
                    }
                    return false
                })
                med.is_current = hasCurrentAppointment ? 1 : 0
            }
        }
    })

    // 根据is_current对房间进行排序，有当前预约的排在后面
    过滤后的房间数据.sort((a, b) => {
        if (a.is_current === b.is_current) {
            return 0
        }
        return a.is_current ? 1 : -1
    })

    // 根据is_current对治疗师进行排序，有当前预约的排在后面
    过滤后的治疗师数据.sort((a, b) => {
        if (a.is_current === b.is_current) {
            return 0
        }
        return a.is_current ? 1 : -1
    })
    rooms.value = 过滤后的房间数据
    medicals.value = 过滤后的治疗师数据
}

// 启动定时器
function startExpirationCheck() {
    if (timer) {
        clearInterval(timer)
    }
    timer = window.setInterval(checkAndRemoveExpiredAppointments, 1000)
}

function handleRefreshAppointments() {
    fetchData()
}
// 组件挂载时启动定时器
onMounted(() => {
    generateDateButtons()
    fetchData()
    fetchFormHealthItems('') // 初始化养生项目数据
    startExpirationCheck()
})

// 监听appointment_date变化，更新按钮选中状态
// watch(() => bookingForm.value.appointment_date, (newDate) => {
//     if (dateButtons.value.length > 0) {
//         dateButtons.value.forEach(button => {
//             button.isSelected = button.value === newDate
//         })
//     }
// })

// 组件卸载时清除定时器
onUnmounted(() => {
    if (timer) {
        clearInterval(timer)
        timer = null
    }
})
</script>

<style scoped lang="scss">
.appointment-page {
    background: #f0f7ff;
    padding: 10px;
    min-height: 100vh;

    :deep(.help-icon) {
        font-size: 16px !important;
        color: #909399 !important;
        opacity: 0.5 !important;
        margin-left: 4px !important;
    }

    .date-picker-container {
        background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
        border-radius: 10px;
        padding: 5px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
        margin-bottom: 5px;
        border: 1px solid rgba(0, 123, 255, 0.1);

        .date-picker-header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .header-left {
                display: flex;
                align-items: center;
            }

            .el-icon {
                font-size: 22px;
                margin-right: 10px;
                color: #007bff;
            }

            .date-picker-title {
                font-size: 14px;
                font-weight: 600;
                color: #2c3e50;
                letter-spacing: 0.5px;
            }

            .help-icon {
                margin-left: 8px;
                color: #6c757d;
                cursor: help;
            }

            .header-actions {
                .el-button {
                    .el-icon {
                        margin-right: 4px;
                    }
                }

                .add-appointment-btn {
                    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
                    border: none;
                    padding: 12px 24px;
                    border-radius: 8px;
                    box-shadow: 0 4px 12px rgba(0, 123, 255, 0.2);
                    transition: all 0.3s ease;

                    &:hover {
                        transform: translateY(-2px);
                        box-shadow: 0 6px 16px rgba(0, 123, 255, 0.3);
                        background: linear-gradient(135deg, #0056b3 0%, #004494 100%);
                    }

                    &:active {
                        transform: translateY(0);
                        box-shadow: 0 2px 8px rgba(0, 123, 255, 0.2);
                    }

                    .plus-icon {
                        font-size: 20px;
                        font-weight: bold;
                        margin-right: 8px;
                        vertical-align: middle;
                        color: #ffffff;
                        padding: 4px;
                        border-radius: 4px;
                    }
                }
            }
        }

        .date-buttons-container {
            display: flex;
            justify-content: center;
            margin-top: 10px;
            padding: 10px 0;
            border-top: 1px solid rgba(0, 123, 255, 0.1);

            .date-buttons {
                display: flex;
                gap: 8px;
                flex-wrap: wrap;
                justify-content: center;

                .date-button {
                    min-width: 60px;
                    padding: 8px 12px;
                    border-radius: 6px;
                    font-size: 13px;
                    font-weight: 500;
                    transition: all 0.3s ease;
                    border: 1px solid rgba(0, 123, 255, 0.2);
                    position: relative;

                    &:hover {
                        transform: translateY(-1px);
                        box-shadow: 0 2px 8px rgba(0, 123, 255, 0.15);
                    }

                    &.el-button--primary {
                        background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
                        border-color: #007bff;

                        &:hover {
                            background: linear-gradient(135deg, #0056b3 0%, #004494 100%);
                        }
                    }

                    &.el-button--default {
                        background: #ffffff;
                        color: #495057;

                        &:hover {
                            background: rgba(0, 123, 255, 0.05);
                            color: #007bff;
                            border-color: #007bff;
                        }
                    }

                    &.el-button--success {
                        background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);
                        border-color: #28a745;
                        color: #ffffff;

                        &:hover {
                            background: linear-gradient(135deg, #1e7e34 0%, #155724 100%);
                        }
                    }

                    &.selected-date {
                        position: relative;
                        cursor: pointer;

                        &::after {
                            content: '👆';
                            position: absolute;
                            bottom: -20px;
                            left: 50%;
                            transform: translateX(-50%);
                            font-size: 16px;
                            line-height: 1;
                            z-index: 10;
                        }
                    }

                    .appointment-badge {
                        position: absolute !important;
                        top: -8px !important;
                        right: -8px !important;
                        z-index: 10 !important;
                    }
                }
            }
        }
    }

    .appointment-main {
        padding: 5px;

        .main-tabs {
            :deep(.el-tabs__header) {
                margin-bottom: 20px;
            }
        }

        .dimensions-container {
            display: flex;
            justify-content: space-between;
            gap: 3px;
        }

        .dimension-container {
            flex: 1;
            background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
            border-radius: 10px;
            padding: 5px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            border: 1px solid rgba(0, 123, 255, 0.1);

            .dimension-header {
                display: flex;
                align-items: center;
                margin-bottom: 5px;
                padding-bottom: 5px;
                padding-top: 5px;
                border-bottom: 1px solid rgba(0, 123, 255, 0.1);

                .el-icon {
                    font-size: 22px;
                    margin-right: 10px;
                }

                .dimension-title {
                    font-size: 16px;
                    font-weight: 600;
                    color: #2c3e50;
                    letter-spacing: 0.5px;
                }

                .help-icon {
                    margin-left: 8px;
                    color: #6c757d;
                    cursor: help;
                }
            }
        }

        .room-dimension {
            .el-icon {
                color: #007bff;
            }

            .room-card {
                border: 2px solid #007bff;
                background: linear-gradient(to bottom right, #ffffff, #f0f7ff);
                transition: all 0.3s ease;
                position: relative;

                &:hover {
                    box-shadow: 0 6px 20px rgba(0, 123, 255, 0.15);
                    transform: translateY(-2px);
                }

                &.current-appointment {
                    border-color: #ffc107;
                }

                .card-title {
                    color: #0056b3;
                }

                .today-appointment {
                    color: #007bff;
                }

                .not-today-appointment {
                    color: #6c757d;
                }
            }
        }

        .medical-dimension {
            .el-icon {
                color: #28a745;
            }

            .medical-card {
                border: 2px solid #28a745;
                background: linear-gradient(to bottom right, #ffffff, #f0fff4);
                transition: all 0.3s ease;
                position: relative;

                &:hover {
                    box-shadow: 0 6px 20px rgba(40, 167, 69, 0.15);
                    transform: translateY(-2px);
                }

                &.current-appointment {
                    border-color: #dc3545;
                }

                .card-title {
                    color: #218838;
                }

                .today-appointment {
                    color: #28a745;
                }

                .not-today-appointment {
                    color: #6c757d;
                }
            }
        }

        .room-cards,
        .medical-cards {
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            gap: 5px;
            width: 100%;

            @media screen and (min-width: 1800px) {
                grid-template-columns: repeat(3, minmax(0, 1fr));
            }

            @media screen and (max-width: 1400px) {
                grid-template-columns: repeat(2, minmax(0, 1fr));
            }

            @media screen and (max-width: 768px) {
                grid-template-columns: repeat(1, minmax(0, 1fr));
            }
        }

        .card {
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            background: #fff;
            padding: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            min-height: 120px;
            width: 100%;
            box-sizing: border-box;
        }

        .card-title {
            font-weight: 600;
            margin-bottom: 12px;
            font-size: 16px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            letter-spacing: 0.5px;
        }

        .card-content {
            color: #2c3e50;
            font-size: 15px;

            .today-appointment {
                font-weight: 500;
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 8px 12px;
                border-radius: 8px;
                transition: all 0.3s;
                margin-bottom: 8px;
                background: rgba(0, 123, 255, 0.05);

                &:hover {
                    background-color: rgba(0, 123, 255, 0.1);
                }

                .appointment-info {
                    flex: 1;
                    margin-right: 8px;
                    white-space: normal !important;
                    word-break: break-all !important;
                    overflow: visible !important;
                    text-overflow: unset !important;
                }

                .cancel-btn {
                    margin-left: 8px;
                    padding: 4px 8px;
                    font-size: 12px;
                    height: auto;
                    line-height: 1;
                    border: none;
                    background: transparent;
                    color: #6c757d;
                    transition: all 0.3s ease;

                    &:hover {
                        color: #dc3545;
                        background: transparent;
                    }

                    &:active {
                        color: #dc3545;
                        background: transparent;
                    }
                }
            }

            .not-today-appointment {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 4px 4px;
                border-radius: 4px;
                transition: all 0.3s;
                margin-bottom: 8px;
                background: rgba(108, 117, 125, 0.05);

                &:hover {
                    background-color: rgba(108, 117, 125, 0.1);
                }

                .appointment-info {
                    flex: 1;
                    margin-right: 8px;
                    white-space: normal !important;
                    word-break: break-all !important;
                    overflow: visible !important;
                    text-overflow: unset !important;
                    line-height: 1.5 !important;
                }

                .cancel-btn {
                    margin-left: 8px;
                    padding: 4px 8px;
                    font-size: 12px;
                    height: auto;
                    line-height: 1;
                    border: none;
                    background: transparent;
                    color: #6c757d;
                    transition: all 0.3s ease;

                    &:hover {
                        color: #dc3545;
                        background: transparent;
                    }

                    &:active {
                        color: #dc3545;
                        background: transparent;
                    }
                }
            }

            .more-btn {
                margin-top: 12px;
                font-weight: 500;
            }

            .symptoms-line {
                margin-top: 4px;
                margin-bottom: 4px;
                padding-left: 4px;
            }

            .symptoms-text {
                color: #c6c7a7;
                font-size: 12px;
                display: block;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                cursor: pointer;
                transition: color 0.3s ease;

                &:hover {
                    color: #cc9d8d;
                }
            }

            .today-title,
            .future-title {
                font-size: 14px;
                color: #495057;
                margin: 12px 0;
                font-weight: 600;
            }

            .future-title {
                margin-top: 10px;
            }

            span {
                display: block;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }
    }

    .arrow-icon {
        margin-left: 6px;
        transition: transform 0.3s ease;
        font-size: 14px;
        vertical-align: middle;

        &.is-expanded {
            transform: rotate(180deg);
        }
    }
}

// 弹窗tab样式
:deep(.dialog-tabs) {
    .el-tabs__header {
        margin-bottom: 20px;
    }

    .el-tabs__nav-wrap {
        padding: 0 20px;
    }

    .el-tabs__item {
        font-weight: 500;
        font-size: 16px;
    }

    .el-tabs__item.is-active {
        color: #409eff;
    }
}
</style>
